import http from 'http';

import { nanoid } from 'nanoid';
import { WebSocketServer, WebSocket } from 'ws';

import { SERVER } from '../loadConfig.ts';

let wss: WebSocketServer | null = null;
const connMap = new Map<string, WebSocket>();

export function wssInit(server: http.Server) {
  // 创建 WebSocket 服务器
  wss = new WebSocketServer({ noServer: true });

  // 处理 WebSocket 升级请求
  server.on('upgrade', async (request, socket, head) => {
    try {
      if (!request.url!.startsWith(SERVER.WS.PATH)) {
        socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
        socket.destroy();
        return;
      }

      // 解析 URL 查询参数
      const url = new URL(request.url as string, `http://${request.headers.host}`);
      const token = url.searchParams.get('token');

      if (!token) {
        socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
        socket.destroy();
        return;
      }

      // todo 验证 token
      // const decoded = jwt.verify(token, SECRET_KEY);
      // console.log('Token verified:', decoded);

      // 获取用户 ID
      // const userId = decoded.userId;
      const userId = nanoid();

      // 如果 token 验证成功，则将连接升级为 WebSocket
      wss!.handleUpgrade(request, socket, head, (ws) => {
        wss!.emit('connection', ws, request, userId);
      });
    } catch (err) {
      if (err instanceof Error) {
        console.error('Catch code error:', err.message);
        socket.write('HTTP/1.1 500 Internal Server Error\r\n\r\n');
      } else {
        console.error('unknown error:', err);
      }
      socket.destroy();
    }
  });
  wssOnConn(wss);
}

function wssOnConn(wss: WebSocketServer) {
  wss.on('connection', (conn, _, ...args: [string]) => {
    const userId = args[0];

    // 将用户 ID 和 WebSocket 实例存储在 map 中
    connMap.set(userId, conn);

    // 监听客户端消息
    conn.on('message', (message) => {
      try {
        const data = JSON.parse(message as any);
        conn.send(JSON.stringify({ message: 'message arrived' }));
        console.log('Received message:', data);
      } catch (err) {
        console.log(err);
      }
    });

    // 处理客户端断开连接
    conn.on('close', () => {
      console.log(`Client disconnected with user ID: ${userId}`);
      connMap.delete(userId);
    });
  });
}
